package pers.xx.sbm.service.serviceImpl;

/**
 * @author ：xiexing
 * @description：
 * @date ：2020/12/10 14:06
 */

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pers.xx.sbm.entity.User;
import pers.xx.sbm.service.ImportExcelService;
import pers.xx.sbm.utils.ImportExcelUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImportExcelServiceImpl extends ImportExcelUtils implements ImportExcelService {

    public List<User> importExcelWithSimple(MultipartFile file) {
        int rowNum = 0;//已取值的行数
        int colNum = 0;//列号
        int realRowCount = 0;//真正有数据的行数

        //得到工作空间
        Workbook workbook = null;
        try {
            workbook = super.getWorkbookByInputStream(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //得到工作表
        Sheet sheet = super.getSheetByWorkbook(workbook, 0);
        if (sheet.getRow(2000) != null) {
            throw new RuntimeException("系统已限制单批次导入必须小于或等于2000笔！");
        }

        realRowCount = sheet.getPhysicalNumberOfRows();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<User> list = new ArrayList<>();

        for (Row row : sheet) {
            if (realRowCount == rowNum) {
                break;
            }

            if (super.isBlankRow(row)) {//空行跳过
                continue;
            }

            if (row.getRowNum() == -1) {
                continue;
            } else {
                if (row.getRowNum() == 0) {//第一行表头跳过
                    continue;
                }
            }

            rowNum++;
            colNum = 0;
            User user = new User();

            super.validCellValue(sheet, row, ++colNum, "姓名");
            user.setUserName(super.getCellValue(sheet, row, colNum - 1));

            super.validCellValue(sheet, row, ++colNum, "性别");
            user.setUserGender(super.getCellValue(sheet, row, colNum - 1));

            super.validCellValue(sheet, row, ++colNum, "账号");
            user.setUserAccount(super.getCellValue(sheet, row, colNum - 1));

            super.validCellValue(sheet, row, ++colNum, "电话");
            user.setUserPhone(super.getCellValue(sheet, row, colNum - 1));

            super.validCellValue(sheet, row, ++colNum, "邮箱");
            user.setUserEmail(super.getCellValue(sheet, row, colNum - 1));

            super.validCellValue(sheet, row, ++colNum, "地址");
            user.setUserAddress(super.getCellValue(sheet, row, colNum - 1));
            list.add(user);
        }

        return list;
    }
}